import {ActivatedRouteSnapshot, CanActivate, CanLoad, Route, Router, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs';
import {Injectable} from '@angular/core';
import {Url} from '../enums/url';
import {AuthService} from './auth.service';
import {globalCache} from '../commons/cache.manage';
import { AccountData } from '../account/account.data';

/**
 * 认证服务接口
 * @author 王锦阳
 * @version 1.0
 * @since 2018/09/19
 */
@Injectable({
    providedIn: 'root'
})
export class Authentication implements CanActivate, CanLoad {

    constructor(private authService: AuthService, private router: Router) {
    }

    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.doAuthentication(state.url);
    }

    public canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
        return this.doAuthentication(route.path);
    }

    private doAuthentication(urlString: string): boolean {
        const user: AccountData = globalCache.getUser();
        if (user) {
            return true;
        }
        this.authService.redirectTo = Url.urlOf(urlString);
        this.router.navigateByUrl(Url.LOGIN.url).then(Url.jumpVerify);
        return false;
    }

}
